package com.heima.search.service.impl;

import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.HistorySearchDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.search.pojos.ApUserSearch;
import com.heima.search.service.ApUserSearchService;
import com.heima.utils.thread.AppThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class ApUserSearchServiceImpl implements ApUserSearchService {
    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 保存用户搜索历史记录
     *
     * @param keyword
     * @param userId 异步调用，无法通过AppThreadLocalUtil获取用户id
     */
    @Override
    @Async
    public void insert(String keyword, Integer userId) {
        //1.查询当前用户的搜索关键词
        ApUserSearch userSearch = mongoTemplate.findOne(Query.query(Criteria.where("keyword").is(keyword)
                .and("userId").is(userId)), ApUserSearch.class);
        //2.存在 更新创建时间
        if (userSearch != null) {
            userSearch.setCreatedTime(new Date());
            mongoTemplate.save(userSearch);
            return;
        }

        //3.不存在，判断当前历史记录总数量是否超过10
        //查到该用户的所有记录
       /* List<ApUserSearch> searchList = mongoTemplate.find(Query.query(Criteria.where("userId").is(userId)), ApUserSearch.class);
        //用户记录为空或条数小于10,直接保存
        if (searchList == null || searchList.size() < 10) {
            mongoTemplate.save(userSearch);
        } else {
            //搜索历史大于10条，替换最后一条
            ApUserSearch lastUserSearch = searchList.get(searchList.size() - 1);
            mongoTemplate.findAndReplace(Query.query(Criteria.where("id").is(lastUserSearch.getId())),userSearch));
        }*/

        //3.不存在，直接添加搜索历史
        userSearch = new ApUserSearch();
        userSearch.setUserId(userId);
        userSearch.setKeyword(keyword);
        userSearch.setCreatedTime(new Date());

        mongoTemplate.save(userSearch);
    }

    /**
     * 查询用户搜索历史，只获取前10条
     * @return
     */
    @Override
    public ResponseResult findUserSearch() {
        //获取用户，判断用户是否登录
        ApUser user = AppThreadLocalUtil.getUser();
        if(user == null ){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //根据用户查询，并且按照时间排序，并只获取前10条
        List<ApUserSearch> searchList = mongoTemplate.find(Query.query(Criteria.where("userId").is(user.getId()))
                .with(Sort.by(Sort.Direction.DESC, "createdTime"))
                .limit(10), ApUserSearch.class);
        return ResponseResult.okResult(searchList);
    }

    /**
     * 删除搜索历史记录
     * @param historySearchDto
     * @return
     */
    @Override
    public ResponseResult delUserSearch(HistorySearchDto historySearchDto) {
        //检查参数
        if(historySearchDto == null || historySearchDto.getId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        ApUser user = AppThreadLocalUtil.getUser();
        if(user == null ){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //根据用户id和历史记录id删除数据库中记录
        mongoTemplate.remove(Query.query(Criteria.where("id").is(historySearchDto.getId())
                .and("userId").is(user.getId()))
                ,ApUserSearch.class);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
